package datastructure.matrix;

/**
 *
 * @author Lei
 */
public class PrintMatrixInSpiralOrder {

    public static void printMatrixInSpiralOrder(int[][] matrix, int m, int n, int k) {
        if (m < 0 || n < 0) {
            return;
        }

        if (m == 1) {
            for (int j = 0; j < n; j++) {
                System.out.println(matrix[k][k + j] + " ");
            }
        }

        if (n == 1) {
            for (int i = 0; i < m; i++) {
                System.out.println(matrix[k + i][k]);
            }
            return;
        }

        // print from top left
        for (int j = 0; j < n - 1; j++) {
            System.out.println(matrix[k][k + j]);
        }
        // print from top right
        for (int i = 0; i < m - 1; i++) {
            System.out.println(matrix[k + i][k + n - 1]);
        }
        // print from bottom right
        for (int j = 0; j < n - 1; j++) {
            System.out.println(matrix[k + m - 1][k + n - 1 - j]);
        }
        // print from bottom left
        for (int i = 0; i < m - 1; i++) {
            System.out.println(matrix[k + m - 1 - i][k]);
        }

        printMatrixInSpiralOrder(matrix, m - 2, n - 2, k + 1);
    }

    public static void main(String args[]) {

        int m[][] = {
            {1, 2, 3, 4},
            {8, 7, 6, 5},
            {9, 10, 11, 12},
            {13, 14, 15, 16}
        };

        PrintMatrixInSpiralOrder.printMatrixInSpiralOrder(m, 4, 4, 0);

    }
}
